package top.codedance.iotp.loadblance.algorithm;

import top.codedance.iotp.loadblance.entiy.RegistyUri;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Random extends Adapter {
    private List<RegistyUri> tmpRegistyUris = new ArrayList<>();
    @Override
    public String execute(List<RegistyUri> registyUris, Func<String> func) {
        for(RegistyUri ru : registyUris){
            tmpRegistyUris.add(ru);
        }
        return doRun(func);
    }

    private String doRun(Func<String> func){
        java.util.Random random = new java.util.Random();
        random.setSeed(new Date().getTime());
        int i = random.nextInt(tmpRegistyUris.size() - 1) % tmpRegistyUris.size();
        String result = func.run(tmpRegistyUris.remove(i).getUrl());
        if(result == null){
            if(tmpRegistyUris.size() > 0) {
                doRun(func);
            }
        }
        return result;
    }
}
